package com.ourchem.bus.service.impl;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

import com.ourchem.bus.domain.CountResult;
import com.ourchem.bus.domain.IpView;
import com.ourchem.bus.mapper.IpViewMapper;
import com.ourchem.bus.service.IIpViewService;
import com.ourchem.common.core.redis.RedisCache;
import com.ourchem.common.utils.DateUtils;
import com.ourchem.common.utils.SecurityUtils;
import com.ourchem.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 用户访问量Service业务层处理
 *
 * @author ourchem
 * @date 2021-11-02
 */
@Service
public class IpViewServiceImpl implements IIpViewService {
    @Autowired
    private IpViewMapper ipViewMapper;

    @Autowired
    RedisCache redisCache;

    /**
     * 查询用户访问量
     *
     * @param id 用户访问量主键
     * @return 用户访问量
     */
    @Override
    public IpView selectIpViewById(Integer id) {
        return ipViewMapper.selectIpViewById(id);
    }

    /**
     * 查询用户访问量列表
     *
     * @param ipView 用户访问量
     * @return 用户访问量
     */
    @Override
    public List<IpView> selectIpViewList(IpView ipView) {
        return ipViewMapper.selectIpViewList(ipView);
    }

    /**
     * 新增用户访问量
     *
     * @param ipAddress 用户ip地址
     * @return 结果
     */
    @Override
    public int insertIpView(String ipAddress) {
        if (!StringUtils.isEmpty(ipAddress) && redisCache.setNx("viewCount"+ ipAddress, "成功", 30, TimeUnit.MINUTES)) {
            IpView ipView = new IpView();
            ipView.setIpaddr(ipAddress);
            ipView.setCreateTime(DateUtils.getNowDate());
            return ipViewMapper.insertIpView(ipView);
        }
        return 0;
    }

    /**
     * 修改用户访问量
     *
     * @param ipView 用户访问量
     * @return 结果
     */
    @Override
    public int updateIpView(IpView ipView) {
        return ipViewMapper.updateIpView(ipView);
    }

    /**
     * 批量删除用户访问量
     *
     * @param ids 需要删除的用户访问量主键
     * @return 结果
     */
    @Override
    public int deleteIpViewByIds(Integer[] ids) {
        return ipViewMapper.deleteIpViewByIds(ids);
    }

    /**
     * 删除用户访问量信息
     *
     * @param id 用户访问量主键
     * @return 结果
     */
    @Override
    public int deleteIpViewById(Integer id) {
        return ipViewMapper.deleteIpViewById(id);
    }



    /**
     * 获得用户访问的日量
     */
    @Override
    public int selectIpViewByOneDayCount(String day) {
        return ipViewMapper.selectIpViewByOneDayCount(day).getViewDayCount();
    }

    /**
     * 如果参数是空的话，就默认计算全部
     * 获得用户访问的时间段总量月份
     * 返回结果是一个list list中有很多个日期map（包含天数和对应的浏览量）
     */
    @Override
    public Map selectIpViewByAllMonthsCount(String day1, String day2) {
        if (!StringUtils.isEmpty(day1) && !StringUtils.isEmpty(day2) && day1!=day2) {
            DateFormat df = new SimpleDateFormat("yyyy-MM");
            Date day3 =null;
            Date day4 =null;
            try {
                day3 = df.parse(day1);
                day4 = df.parse(day2);
            } catch (ParseException e) {
                throw  new RuntimeException("解析错误，请传入正确时间");
            }
            int i = ipViewMapper.selectIpViewByAllCount(df.format(day3), df.format(day4)).getViewAllCount();
            List<Map<String, String>> maps = ipViewMapper.selectIpViewByAllMonthsCount(df.format(day3), df.format(day4));
            HashMap map = new HashMap();
            map.put("count", i);
            map.put("dataInfo", maps);
            return map;
        }
        int i = ipViewMapper.selectIpViewByAllCount("","").getViewAllCount();
        List<Map<String, String>> maps = ipViewMapper.selectIpViewByAllMonthsCount("","");
        HashMap map = new HashMap();
        map.put("count", i);
        map.put("dataInfo", maps);
        return map;
    }

    /**
     * 如果参数是空的话，就默认计算全部
     * 获得用户访问的时间段总量
     * 返回结果是一个list list中有很多个日期map（包含天数和对应的浏览量）
     */
    @Override
    public Map selectIpViewByAllDaysCount(String day1, String day2)  {
        if (!StringUtils.isEmpty(day1) && !StringUtils.isEmpty(day2)) {
            Date startDate = DateUtils.parseDate(day1);
            Date endDate = DateUtils.parseDate(day2);
            int count = (int) ((endDate.getTime() - startDate.getTime()) / (24 * 60 * 60 * 1000));
            String[] countArr = new String[count];
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            Date dd = null;
            try {
                dd = df.parse(day2);
            } catch (ParseException e) {
                throw  new RuntimeException("解析错误，请传入正确时间");
            }
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(dd);
            calendar.add(Calendar.DAY_OF_MONTH, 1);//加一天
            int i = ipViewMapper.selectIpViewByAllCount(day1, df.format(calendar.getTime())).getViewAllCount();
            List<Map<String, String>> maps = ipViewMapper.selectIpViewByAllDaysCount(day1, countArr);
            HashMap map = new HashMap();
            map.put("count", i);
            map.put("dataInfo", maps);
            return map;
        }
        //最小时间
        String day3 = ipViewMapper.selectIpViewByMinDay();
        Date startDate = DateUtils.parseDate(day3);
        //最大时间
        String day4 = ipViewMapper.selectIpViewByMaxDay();
        Date endDate = DateUtils.parseDate(day4);
        int count = (int) ((endDate.getTime() - startDate.getTime()) / (24 * 60 * 60 * 1000));
        String[] countArr = new String[count];
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date dd = null;
        try {
            dd = df.parse(day4);
        } catch (ParseException e) {
            throw  new RuntimeException("解析错误，请传入正确时间");
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dd);
        calendar.add(Calendar.DAY_OF_MONTH, 1);//加一天
        int i = ipViewMapper.selectIpViewByAllCount(day3, df.format(calendar.getTime())).getViewAllCount();
        List<Map<String, String>> maps = ipViewMapper.selectIpViewByAllDaysCount(day3, countArr);
        HashMap map = new HashMap();
        map.put("count", i);
        map.put("dataInfo", maps);
        return map;
    }

}
